package com.leetcode.tree.bst;

import com.leetcode.basic.TreeNode;

/**
 * @author Dennis Li
 * @date 2020/6/16 22:06
 */
public class TrimBST_669 {
    public TreeNode trimBST1(TreeNode root, int L, int R) {
        if (root == null) return null;
        // 如果结点值比R大，那么放弃当前结点，转去左子树
        if (root.val > R) return trimBST(root.left, L, R);
        // 右子树同理
        if (root.val < L) return trimBST(root.right, L, R);
        // 将左右子树都修剪至满足条件
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        return root;
    }

    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null) return null;
        if (root.val < L) {
            root = trimBST(root.right, L, R);
        } else if (root.val > R) {
            root = trimBST(root.left, L, R);
        } else {
            root.left = trimBST(root.left, L, root.val);
            root.right = trimBST(root.right, root.val, R);
        }
        return root;
    }
}
